#!/bin/bash

# 洗护系统数据库恢复脚本

set -e

# 配置
DB_CONTAINER="laundry-mysql"
DB_NAME="laundry_care"
DB_USER="laundry_user"
DB_PASSWORD="LaundryPass2024!"
BACKUP_DIR="backups/database"

# 显示帮助信息
show_help() {
    echo "用法: $0 <backup_file>"
    echo ""
    echo "参数:"
    echo "  backup_file    备份文件路径（支持.sql或.sql.gz格式）"
    echo ""
    echo "示例:"
    echo "  $0 backups/database/laundry_care_20241215_120000.sql.gz"
    echo "  $0 backups/database/laundry_care_20241215_120000.sql"
    echo ""
    echo "可用备份文件:"
    if [ -d "$BACKUP_DIR" ]; then
        ls -1 "$BACKUP_DIR"/*.sql.gz 2>/dev/null || echo "  无备份文件"
    else
        echo "  备份目录不存在"
    fi
}

# 检查参数
if [ $# -eq 0 ]; then
    echo "❌ 错误: 请指定备份文件"
    show_help
    exit 1
fi

if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
    show_help
    exit 0
fi

BACKUP_FILE="$1"

# 检查备份文件是否存在
if [ ! -f "$BACKUP_FILE" ]; then
    echo "❌ 错误: 备份文件不存在: $BACKUP_FILE"
    exit 1
fi

echo "🔄 开始数据库恢复..."
echo "数据库: $DB_NAME"
echo "备份文件: $BACKUP_FILE"

# 确认操作
read -p "⚠️ 警告: 此操作将覆盖现有数据库，是否继续？(y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "❌ 操作已取消"
    exit 1
fi

# 检查Docker容器是否运行
if ! docker ps | grep -q "$DB_CONTAINER"; then
    echo "❌ 错误: MySQL容器未运行，请先启动服务"
    exit 1
fi

# 创建临时恢复文件
TEMP_FILE="/tmp/restore_$(date +%s).sql"

# 处理压缩文件
if [[ "$BACKUP_FILE" == *.gz ]]; then
    echo "📦 解压备份文件..."
    gunzip -c "$BACKUP_FILE" > "$TEMP_FILE"
else
    cp "$BACKUP_FILE" "$TEMP_FILE"
fi

# 执行恢复
echo "🔄 执行数据库恢复..."
if docker exec -i "$DB_CONTAINER" mysql \
    -u "$DB_USER" \
    -p"$DB_PASSWORD" \
    "$DB_NAME" < "$TEMP_FILE"; then
    
    echo "✅ 数据库恢复成功"
    
    # 验证恢复结果
    echo "🔍 验证恢复结果..."
    TABLE_COUNT=$(docker exec "$DB_CONTAINER" mysql \
        -u "$DB_USER" \
        -p"$DB_PASSWORD" \
        -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_NAME';" \
        -s -N)
    
    echo "📊 恢复后表数量: $TABLE_COUNT"
    
else
    echo "❌ 数据库恢复失败"
    rm -f "$TEMP_FILE"
    exit 1
fi

# 清理临时文件
rm -f "$TEMP_FILE"

echo "🎉 数据库恢复完成！"
echo "💡 建议重启后端服务以确保数据一致性"
